package com.zzyl.nursing.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.mapper.BedMapper;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

/**
 * 入住Service业务层处理
 * 
 * @author alexis
 * @date 2025-06-07
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private IBedService  bedService;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private IElderService elderService;

    @Autowired
    private IContractService contractService;

    @Autowired
    private ICheckInService checkInService;

    @Autowired
    private ICheckInConfigService checkInConfigService;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    /**
     * 申请入住
     *
     * @param checkInApplyDto
     */
    @Override
    public void applyChickIn(CheckInApplyDto checkInApplyDto) {
        try {
            //判断老人是否已入住
            //复制属性
            String idCardNo = checkInApplyDto.getCheckInElderDto().getIdCardNo();
            LambdaQueryWrapper<CheckIn> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CheckIn::getIdCardNo,idCardNo);
            CheckIn oneCheckIn = getOne(queryWrapper);
            if (oneCheckIn != null&&oneCheckIn.getStatus()==0){
                throw new BaseException("老人已入住");
            }
            //更新床位状态为已入住
            Long bedId = checkInApplyDto.getCheckInConfigDto().getBedId();
            bedMapper.updateBedStatusById(bedId,1);
            //新增或更新老人
            //查询是否有老人信息
            LambdaQueryWrapper<Elder> elderWrapper = new LambdaQueryWrapper<>();
            elderWrapper.eq(Elder::getIdCardNo,idCardNo);
            Elder elderOne = elderService.getOne(elderWrapper);
            //复制属性
            Elder elder=new Elder();
            BeanUtils.copyProperties(checkInApplyDto.getCheckInElderDto(),elder);
            elder.setStatus(1);
            elder.setBedId(bedId);
            //获取床位信息
            Bed bed = bedService.getById(bedId);
            elder.setBedNumber(bed.getBedNumber());
            if(elderOne!=null){
                //修改老人信息
                elderService.updateElder(elder);
            }
            else {
                //新增老人属性
                elderService.insertElder(elder);
            }
            //新增签约办理
            //属性拷贝
            Contract contract=new Contract();
            BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(),contract);
            //补全属性
            contract.setElderId(Math.toIntExact(elder.getId()));
            // 生成合同编号
            String contractNo = "HT" + CodeGenerator.generateContractNumber();
            contract.setContractNumber(contractNo);
            contract.setElderName(elder.getName());
            //获取入住配置信息
            CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
            LocalDateTime checkInStartTime = checkInConfigDto.getStartDate();
            LocalDateTime checkInEndTime = checkInConfigDto.getEndDate();
            Integer status = checkInStartTime.isBefore(LocalDateTime.now()) ? 0 : 1;
            contract.setStatus(status);
            contract.setStartDate(checkInStartTime);
            contract.setEndDate(checkInEndTime);
            contractService.insertContract(contract);
            //新增入住信息
            CheckIn checkIn=CheckIn.builder()
                    .elderId(elder.getId())
                    .elderName(elder.getName())
                    .idCardNo(elder.getIdCardNo())
                    .startDate(checkInStartTime)
                    .endDate(checkInEndTime)
                    .nursingLevelName(checkInConfigDto.getNursingLevelName())
                    .bedNumber(bed.getBedNumber())
                    .status(status)
                    .sortOrder(0)
                    .build();
            //补全家属信息
            checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));

            checkInService.insertCheckIn(checkIn);
            //新增入住配置信息
            //拷贝属性
            CheckInConfig checkInConfig=new CheckInConfig();
            BeanUtils.copyProperties(checkInConfigDto,checkInConfig);
            //补全属性
            checkInConfig.setCheckInId(checkIn.getId());
            checkInConfig.setSortOrder(0);
            checkInConfigService.insertCheckInConfig(checkInConfig);
        } catch (BaseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo chickInDetail(Integer id) {
        //查询入住信息
        CheckIn checkIn = checkInService.getById(id);
        //查询老人信息
        Elder elder = elderService.getById(checkIn.getElderId());
        //根据老人生日算出年龄
        String birthday = elder.getBirthday();
        //构建模版将生日转换为LocalDate类型
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate birthDate = LocalDate.parse(birthday, formatter);
        LocalDate now = LocalDate.now();
        int age = Period.between(birthDate, now).getYears();
        //复制属性
        CheckInElderVo checkInElderVo=new CheckInElderVo();
        BeanUtils.copyProperties(elder,checkInElderVo);
        //补全年龄属性
        checkInElderVo.setAge(age);
        //将json字符串转换为家属属性
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(remark, ElderFamilyVo.class);
        //查询入住配置数据
        LambdaQueryWrapper<CheckInConfig> checkInConfigWrapper = new LambdaQueryWrapper<>();
        checkInConfigWrapper.eq(CheckInConfig::getCheckInId,id);
        CheckInConfig checkInConfig = checkInConfigService.getOne(checkInConfigWrapper);
        //复制属性
        CheckInConfigVo checkInConfigVo=new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        //补全属性
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        //查询合同信息
        LambdaQueryWrapper<Contract> contractWrapper = new LambdaQueryWrapper<>();
        contractWrapper.eq(Contract::getElderId,elder.getId());
        Contract contract = contractService.getOne(contractWrapper);

        //组成返回数据
        CheckInDetailVo  checkInDetailVo=new CheckInDetailVo();
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setContract(contract);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);


        return checkInDetailVo;
    }
}
